package com.paradogs.framework.server;

import com.paradogs.framework.database.ParadogsDBAsyncThread;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * @author: yumi
 * @date: 2024/4/24  17:47
 * @Description: TODO
 */
@Slf4j
@Component
public class SpringApplicationHook {

    /** 服务器关闭 */
    @EventListener(ContextClosedEvent.class)
    public void handleContextClosedEvent(ContextClosedEvent evt) throws InterruptedException {
        log.info("SpringApplicationHook ContextClosedEvent start ...");

        // 关闭服务器
        if (ParadogsServerHolder.server != null) {
            ParadogsServerHolder.server.close().sync();
        }
        log.warn("已关闭服务器...");

        // 关闭游戏线程
        ParadogsGameLogicHandleThread.stop();
        while (!ParadogsGameLogicHandleThread.isAlreadyStop());
        log.warn("已关闭游戏线程...");

        // 关闭持久化线程
        ParadogsDBAsyncThread.shutdown();
        while (!ParadogsDBAsyncThread.isAlreadyShutdown());
        log.warn("已关闭持久化线程...");

        log.info("SpringApplicationHook ContextClosedEvent end ...");
    }

}
